const Router = require('koa-router');
const router = new Router({ prefix: '/api/appointments' });
const { Appointment } = require('../models/appointmentsModels');

// 提交预约
router.post('/submit', async (ctx) => {
  try {
    const appointmentData = ctx.request.body;
    console.log('预约数据:', appointmentData);

    // 验证必填字段
    const requiredFields = ['department', 'doctor', 'doctor_title', 'date', 'time', 'patient_name', 'patient_phone'];
    for (const field of requiredFields) {
      if (!appointmentData[field]) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: `缺少必填字段: ${field}`
        };
        return;
      }
    }

    // 处理日期格式转换，确保正确存储为DATE类型
    let appointmentDate = appointmentData.date;
    if (typeof appointmentDate === 'string') {
      // 尝试将字符串转换为Date对象
      const parsedDate = new Date(appointmentDate);
      if (!isNaN(parsedDate.getTime())) {
        appointmentDate = parsedDate;
      } else {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '日期格式无效'
        };
        return;
      }
    }

    // 创建新的预约记录
    const newAppointment = await Appointment.create({
      department: appointmentData.department,
      doctor: appointmentData.doctor,
      doctor_title: appointmentData.doctor_title,
      doctor_id: appointmentData.doctor_id || 1, // 提供默认值
      date: appointmentDate,
      time: appointmentData.time,
      patient_name: appointmentData.patient_name,
      patient_phone: appointmentData.patient_phone,
      clinic_id: appointmentData.clinic_id || 1, // 提供默认值
      user_id: appointmentData.user_id || 1, // 提供默认值
      status: appointmentData.status || 'pending'
    });

    console.log('预约成功，已存储记录:', newAppointment);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: '预约成功',
      data: newAppointment
    };
  } catch (error) {
    console.error('预约失败：', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '预约失败，请稍后重试',
      error: error.message
    };
  }
});

// 获取所有预约记录
router.get('/orders', async (ctx) => {
  try {
    const { department } = ctx.query;
    const where = {};

    if (department) {
      where.department = department;
    }

    const appointments = await Appointment.findAll({ where });
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: '获取预约记录成功',
      data: appointments
    };
  } catch (error) {
    console.error('获取预约记录失败：', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '获取预约记录失败，请稍后重试',
      error: error.message
    };
  }
});

module.exports = router;